function messmatrix=niDaqAi(devname,numofchans,samprate,samptime)
% function messmatrix=niDaqAi(devname,numofchans,samprate,samptime)
% 2021, written by wzb
% Reference:https://www.jensroesner.com/work/matlab/index.html
% provides access of NI's NI-DAQmx driver from Matlab
% Analog Input
% Measures the first numofchans channels.

%errMsg = ''
%errMsgP = libpointer('cstring',errMsg);

if ~libisloaded('myni')
    disp('Matlab: Load nicaiu.dll')
    fdll = 'C:\Windows\System32\nicaiu.dll';
    fheader = 'C:\Program Files (x86)\National Instruments\Shared\ExternalCompilerSupport\C\include\NIDAQmx.h';
    % [funclist warning] = loadlibrary(fdll,@nidaqprototype,'alias','myni');
    [funclist warning] = loadlibrary(fdll,fheader,'alias','myni');
    %if you do NOT have nicaiu.dll and nidaqmx.h
    %in your Matlab path, add full pathnames or copy the files.
    %libfunctions('myni','-full') % use this to show the...
    %libfunctionsview('myni')     % included function
end
disp('Matlab: dll loaded')
disp('')

disp('NI: Define constants')
% Other constants must be searched in the NI installation directory
DAQmx_Val_Volts= 10348; % measure volts
DAQmx_Val_Rising = 10280; % Rising
DAQmx_Val_FiniteSamps = 10178; % Finite Samples
DAQmx_Val_RSE = 10083;
DAQmx_Val_Diff = 10106;
disp('NI: Create Tasks')
%taskh1=uint32(1);
taskh1=uint32([]);
[a,b,taskh1] = calllib('myni','DAQmxCreateTask','',taskh1);
% a will be the error code
%if a<0
%    calllib('myni','DAQmxGetErrorString',a,errMsgP,100)
%    disp(errMsg)
%end

disp('NI: Create AI Channels')
taskchans1=[devname ':' num2str(numofchans-1)];

[a,b,c,d] = calllib('myni','DAQmxCreateAIVoltageChan',(taskh1),taskchans1,'',DAQmx_Val_Diff ,-10,10,DAQmx_Val_Volts,'')

nsample=samprate*samptime; %

disp('NI: Config Sample Clock')
[a,b]=calllib('myni','DAQmxCfgSampClkTiming',taskh1,'',samprate,DAQmx_Val_Rising,...
      DAQmx_Val_ContSamps,nsample);

disp('NI: Start task(s)')
[a]=calllib('myni','DAQmxStartTask',taskh1);

DAQmx_Val_GroupByScanNumber = 1;
readarray1=zeros(numofchans,nsample);
readarray1_ptr=libpointer('doublePtr',readarray1);
sampread=0;
sampread_ptr=libpointer('int32Ptr',sampread);
empty=[];
empty_ptr=libpointer('ulongPtr',empty);
arraylength=nsample*numofchans; % more like "buffersize",
disp('NI: Reading Data!')
[a,b,readarray1,sampread,empty]=calllib('myni','DAQmxReadAnalogF64',taskh1,-1,-1,...
     DAQmx_Val_GroupByScanNumber,readarray1_ptr,arraylength,sampread_ptr,empty_ptr);
a
disp('NI: Stop task')
[a] = calllib('myni','DAQmxStopTask',taskh1);

disp('NI: Clear task(s)')
[a] = calllib('myni','DAQmxClearTask',taskh1);

messmatrix=[readarray1'];
disp('NI Daq finished')